﻿Imports LiteDB

Public Class AppFile
    Private mAppFiles As List(Of AppFileItem)
    Public ReadOnly Property AppFileList As List(Of AppFileItem)
        Get
            Return mAppFiles
        End Get
    End Property
    Public ReadOnly Property GetAppFile(SelectedFileID As Integer) As AppFileItem
        Get
            Try
                Return (From x In mAppFiles Where x.FileID = SelectedFileID).First
            Catch ex As Exception
                Return New AppFileItem
            End Try
        End Get
    End Property
    Sub New()
        mAppFiles = New List(Of AppFileItem)
        LoadList()
    End Sub
    Private Sub LoadList()
        Using db As New LiteEngine(gApp.DatabaseFile)
            mAppFiles = (From x In db.GetCollection(Of AppFileItem)(DTAppFiles).All Where x.ApplicationID = gUDApp.SelectedAppID Order By x.Fullname).ToList
        End Using
    End Sub
    Function Save(Data As AppFileItem) As Integer
        Dim tAdd As Boolean
        Dim tNewID As Integer
        Dim n As AppFileItem
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim col = db.GetCollection(Of AppFileItem)(DTAppFiles)

            tAdd = False
            If Data.FileID = 0 Then
                Try
                    tNewID = (From x In col.All Select x.FileID).Max + 1
                Catch ex As Exception
                    tNewID = 1
                End Try
                Data.FileID = tNewID
                tAdd = True
            End If

            If tAdd = False Then
                n = col.FindById(Data.FileID)
                Dim a = (From x In mAppFiles Where x.FileID = Data.FileID).First
                mAppFiles.Remove(a)
            Else
                n = New AppFileItem
                n.FileID = Data.FileID
                n.ApplicationID = Data.ApplicationID
            End If

            n.Fullname = Data.Fullname
            n.Filename = Data.Filename
            n.ReferenceFile = Data.ReferenceFile
            n.UniqueFilename = Data.UniqueFilename
            n.DirectoryID = Data.DirectoryID
            n.FileStatus = Data.FileStatus
            n.IncludeStatus = Data.IncludeStatus
            n.CreateShortCut = Data.CreateShortCut

            If tAdd = True Then
                col.Insert(n)
            Else
                col.Update(n)
            End If
            mAppFiles.Add(n)
        End Using
        Return n.FileID
    End Function
    Sub RemoveFile(SelectedFileID As Integer)
        Using db As New LiteEngine(gApp.DatabaseFile)
            Dim col = db.GetCollection(Of AppFile)(DTAppFiles).Delete(SelectedFileID)
            Dim a = (From x In mAppFiles Where x.FileID = SelectedFileID).First
            mAppFiles.Remove(a)
        End Using
        LoadList()
    End Sub
End Class
